package com.heima.leetcode.practice;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 勾新杰
 * @version 1.0
 * @description: leetcode 129. 求根节点到叶子节点数字之和
 * @date 2025/5/24 23:09
 */
public class E129 {
    public int sumNumbers(TreeNode root) {
        List<Integer> sum = new ArrayList<>();
        sum.add(0);
        preOrder(root, new StringBuilder(), sum);
        return sum.get(0);
    }

    private void preOrder(TreeNode root, StringBuilder curr, List<Integer> sum) {
        if (root == null) return;
        curr.append(root.val);
        if (root.left == null && root.right == null) {
            sum.set(0, sum.get(0) + Integer.parseInt(curr.toString()));
        }
        preOrder(root.left, curr, sum);
        preOrder(root.right, curr, sum);
        curr.deleteCharAt(curr.length() - 1);
    }
}
